package demo6;

//通过浪费一个位置来实现循环队列

public class MyQueue {
    public int[] elem;
    public int rear;
    public int front;

    //无参构造方法
    public MyQueue(int n) {
        this.elem = new int[n + 1];
    }
    //入队
    public void offer(int val) {
        if (isFull()) {
            throw new IsFullException("队列满!");
        }
        this.elem[rear] = val;
        this.rear = (this.rear + 1) % this.elem.length;

    }

    //出队
    public int poll() {
        if (isEmpty()) {
            throw new IsEmptyException("队列为空!");
        }
        int val = this.elem[front];
        this.front = (this.front + 1) % this.elem.length;
        return val;
    }

    //获得对顶元素
    public int peek() {
        if (isEmpty()) {
            throw new IsEmptyException("队列为空!");
        }
        return this.elem[front];
    }

    //获得队列的有效数字的大小
    public int size() {
        if (isEmpty()) {
            return 0;
        }
        if (isFull()) {
            return this.elem.length;
        }
        int curFront = this.front;
        int count = 0;
        while (curFront != this.rear) {
            curFront = (curFront + 1) % this.elem.length;
            count++;
        }
        return count;
    }

    //判读队列是不是对空
    public boolean isEmpty() {
        return this.rear == this.front;
    }
    //判断队列是不是满
    public boolean isFull() {
        return (this.rear + 1) % this.elem.length == this.front;
    }


}
